import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, useResponseError } from '~/utils/response';
import { queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) return unAuthorizedResponse(event);

  try {
    // 读取请求体
    const { action, msdsNo, data } = await readBody(event);

    // 处理 SUBMIT 请求
    if (action === 'submit') {
      if (!msdsNo) return useResponseError('MSDS编号不能为空！');
      if (!data) return useResponseError('提交的数据为空！');

      const parsedData = JSON.parse(data);

      // 处理_X_ROW_KEY字段
      const cleanTable = (table: any[]) => table.map(({ _X_ROW_KEY, ...rest }) => rest);

      parsedData.compInfoTable = cleanTable(parsedData.compInfoTable || []);

      // 处理JSON类型字段
      const jsonFields = ['compInfoTable', 'component', 'ghsHazClass', 'pictogram', 'pkgMark'];
      const processData = Object.entries(parsedData).reduce((acc, [key, value]) => {
        acc[key] = jsonFields.includes(key) ? JSON.stringify(value) : value;
        return acc;
      }, {} as Record<string, any>);

      // 插入数据库（假设表结构包含所有字段）
      const fields = Object.keys(processData).join(', ');
      const placeholders = Object.keys(processData)
        .map(() => '?')
        .join(', ');
      const queryString = `INSERT INTO msdsData (msdsNo, ${fields}) VALUES (?, ${placeholders}) 
                    ON DUPLICATE KEY UPDATE ${Object.keys(processData)
                      .map((k) => `${k}=VALUES(${k})`)
                      .join(', ')}`;

      await queryDatabase(queryString, [msdsNo, ...Object.values(processData)]);
      return useResponseSuccess('提交成功！');
    }

    if (action === 'getInfo') {
      // 冲突校验
      if (msdsNo && data === 'max') return useResponseError('函数调用搞错啦！仔细再看看啦！');

      let queryString,
        params = [];
      if (data === 'max') {
        queryString = 'SELECT msdsNo FROM msdsData ORDER BY msdsNo DESC LIMIT 1';
      } else if (msdsNo) {
        queryString = 'SELECT * FROM msdsData WHERE msdsNo = ?';
        params.push(msdsNo);
      } else {
        queryString = 'SELECT * FROM msdsData';
      }

      const results = <any[]>await queryDatabase(queryString, params);

      // 统一处理空结果
      if (results.length === 0) {
        return data === 'max'
          ? useResponseSuccess('0')
          : useResponseError(msdsNo ? `数据库中无编号为：${msdsNo}！的数据！` : '未获取到任何信息！');
      }
      // 处理返回成功的数据
      return useResponseSuccess(data === 'max' ? results[0].msdsNo : results);
    }

    if (action === 'delete') {
      if (!msdsNo) return useResponseError('MSDS编号不能为空！');
      await queryDatabase('DELETE FROM msdsdata WHERE msdsNo = ?', [msdsNo]);
      return useResponseSuccess('删除成功！');
    }

    // if (action === 'print') {
    //   if (!msdsNo) return useResponseError('MSDS编号不能为空！');
    //   const msdsData = <any[]>await queryDatabase('SELECT * FROM msdsData WHERE msdsNo = ?', [msdsNo]);
    //   if (msdsData.length === 0) return useResponseError('未找到该MSDS编号的数据！');
    //   console.log(msdsData);
    //   return useResponseSuccess(msdsData[0]);

    // }
  } catch (error) {
    console.error('处理失败:', error);
    return useResponseError(error.message);
  }
});
